<template>
  <div class="color-picker">
    <a-popover position="bottom" trigger="click">
      <div class="color-preview" :style="{ backgroundColor: modelValue }"></div>
      <template #content>
        <div class="color-panel">
          <div class="color-options">
            <div 
              v-for="color in presetColors" 
              :key="color" 
              class="color-option" 
              :style="{ backgroundColor: color }"
              @click="handleColorSelect(color)"
            ></div>
          </div>
          <a-input v-model="colorInput" placeholder="#FFFFFF" @change="handleColorInput">
            <template #prefix>#</template>
          </a-input>
        </div>
      </template>
    </a-popover>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: '#1890ff'
  }
})

const emit = defineEmits(['update:modelValue'])

const presetColors = [
  '#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1',
  '#13c2c2', '#eb2f96', '#fa8c16', '#a0d911', '#fadb14'
]

const colorInput = ref(props.modelValue.replace('#', ''))

watch(() => props.modelValue, (newVal) => {
  colorInput.value = newVal.replace('#', '')
})

const handleColorSelect = (color: string) => {
  emit('update:modelValue', color)
  colorInput.value = color.replace('#', '')
}

const handleColorInput = () => {
  const value = colorInput.value
  if (/^[0-9A-Fa-f]{6}$/.test(value)) {
    emit('update:modelValue', `#${value}`)
  }
}
</script>

<style scoped lang="scss">
.color-picker {
  .color-preview {
    width: 32px;
    height: 32px;
    border-radius: 4px;
    border: 1px solid var(--color-border);
    cursor: pointer;
  }
  
  .color-panel {
    padding: 8px;
    width: 200px;
    
    .color-options {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 12px;
      
      .color-option {
        width: 20px;
        height: 20px;
        border-radius: 2px;
        cursor: pointer;
        transition: all 0.2s;
        
        &:hover {
          transform: scale(1.1);
        }
      }
    }
  }
}
</style>